#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    long long maxSumTrionic(vector<int>& nums) {
        vector<int> dp(nums.size());
        cout<<dp[0]<<',';
        int ans = INT_MIN;
        for(int i=1;i<nums.size();i++){
            if(nums[i]<=nums[i-1]){
                dp[i]=dp[i-1];
            }else{
                dp[i]=i;
            }
            cout<<dp[i]<<',';
        }
        cout<<'\n';
        for(int i=1;i<nums.size()-1;i++){
            cout<<"i:"<<i<<'\n';
            if(i+1<nums.size() && dp[i+1]==dp[i])continue;
            if(dp[i]==i)continue;
            if(dp[i]==0 || dp[i+1]==dp[i])continue;
            int l = dp[i],r=i+1;
            int lsum = nums[dp[i]-1],rsum=nums[i+1],rbegin=nums[i+1];
            while(l-1>0 && (l==1||dp[l-1]!=dp[l-2]) && nums[l]>0){
                l--;
                lsum+=nums[l];
                cout<<"l:"<<l<<'\n';
            }
            while(r<nums.size()-1 && (r==nums.size()-1||dp[r]!=dp[r+1])){
                r++;
                rsum+=nums[r];
                cout<<"r:"<<r<<'\n';
            }
            int mid = 0;
            for(int j=dp[i];j<=i;j++){
                mid+=nums[j];
            }
            ans=max(ans,mid+lsum+max(rsum,rbegin));
            cout<<mid+lsum+max(rsum,rbegin)<<'\n';
        }
        return ans;
    }
};

int main(){
    Solution s;
    vector<int> v={1,4,2,7};
    cout<<s.maxSumTrionic(v)<<'\n';
}